package com.ltu.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.Assert;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.config.shiro.ShiroUtil;
import com.ltu.config.shiro.dto.UserDto;
import com.ltu.constant.AccountType;
import com.ltu.constant.CommonConstant;
import com.ltu.domain.mp_entity.OrderDetailEntity;
import com.ltu.domain.mp_entity.UserEntity;
import com.ltu.enums.CommuntiyMenDict.CommuntiyMenEnum;
import com.ltu.mapper.UserMapper;
import com.ltu.model.request.base.BaseFilterPageReq;
import com.ltu.model.request.base.BaseIdReq;
import com.ltu.model.request.user.UpdateUserInfoReq;
import com.ltu.model.request.user.WxMaLoginReq;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.model.response.dto.UserInfoItem;
import com.ltu.service.UserService;
import com.ltu.service.customize.SessionInfoService;
import com.ltu.service.impl.BaseServiceImpl;
import com.ltu.util.BeanMapper;
import com.ltu.util.common.MpPageUtil;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vk@rongding
 * @since 2020-08-15
 */
@RestController
@RequestMapping("/user") 
@Api(tags = "B-会员模块")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController  extends BaseServiceImpl<UserMapper, UserEntity>{
	Logger  log=org.slf4j.LoggerFactory.getLogger(UserController.class);
    private final UserService userService;
    private final AiContextManager aiContextManager;


    @ApiOperation(value="G:获取用户信息")
    @RequestMapping(value="/getUserInfo", method= RequestMethod.POST)
    public CodeDataResp<UserInfoItem> getUserInfo(@RequestBody BaseIdReq baseIdReq) {
        baseIdReq.setId(ShiroUtil.getPrincipalUserId());
        return BeanMapper.copyRespDataItem(userService.getUserInfo(baseIdReq), UserInfoItem.class.getName());
    }

//    @ApiOperation(value="G:更新用户信息")
//    @RequestMapping(value="/updateUserInfo", method= RequestMethod.POST)
    public CodeDataResp updateUserInfo(@Valid @RequestBody UpdateUserInfoReq userReq) {
        userReq.setUserId(ShiroUtil.getPrincipalUserId());
        return BeanMapper.copyRespDataItem(userService.updateUserInfo(userReq), UserInfoItem.class.getName());
    }

    @ApiOperation(value="MP:获取用户列表")
    @RequiresRoles(value={AccountType.ACCOUNT_TYPE_SYS_STAFF})
    @RequestMapping(value="/getList", method= RequestMethod.POST)
    public CodeDataResp<Page<UserEntity>> getList(@RequestBody BaseFilterPageReq<UserEntity> req) {
    	if(req.getEntityParam() == null)
    		req.setEntityParam(new  UserEntity());
    	req.getEntityParam().setDelFlag(0);
    	UserDto  user = ShiroUtil.getPrincipalUser();
    
    	Page<UserEntity> page = MpPageUtil.getCommonPage(req.getPageReq());
		QueryWrapper<UserEntity>  t=new QueryWrapper<UserEntity>();
		t.lambda().eq(UserEntity :: getDelFlag, 0);
		if(req.getEntityParam()!=null) {
			
			if(req.getEntityParam().getStatus()!=null)
				t.eq("u.status", req.getEntityParam().getStatus());
		}
		
		
		
		if(null != req.getKeyWords() && req.getKeyWords().size() > 0) 
			t.apply(getLikeStr(req.getKeyWords(),"u."));
	
			
			
			
    	Page<UserEntity>	 result= this.baseMapper.customisePage(page, t);
    	
		return CodeDataResp.valueOfSuccess(result);
    }
    
    

    
    @ApiOperation(value="获取列表")
    @RequestMapping(value="/getListNoPage", method= RequestMethod.POST)
    @RequiresRoles(value={AccountType.ACCOUNT_TYPE_SYS_STAFF})
    public CodeDataResp<List<UserEntity>> getListNoPage(@RequestBody  BaseFilterPageReq<UserEntity> req ) {
        return super.getMeList(req);
    }
    
   
    @ApiOperation(value="MP:获取用户详细信息")
    @RequestMapping(value="/getDetail", method= RequestMethod.POST)
    public CodeDataResp<UserEntity> getDetail(@RequestBody BaseIdReq baseIdReq) {
        return userService.getDetail(baseIdReq);
    }

    @ApiOperation(value="MP:新增或修改用户")
    @RequestMapping(value="/edit", method= RequestMethod.POST)
    public CodeDataResp edit(@RequestBody UserEntity req) {
    	if(StringUtils.isBlank(req.getId())) {
    		QueryWrapper<UserEntity> wrapper = new QueryWrapper<UserEntity>();
        	wrapper.lambda().eq(UserEntity :: getUserPhone, req.getUserPhone());
        	int addFlag =	super.count(wrapper);
        	if(addFlag>0)
        		 return   CodeDataResp.valueOfFailed("用户已存在请更换手机号码");
    	}
    	if(req.getSessionId()!=null && req.getSessionId() > 0 ) {
    		aiContextManager.bindUser2Session(req.getId(), req.getNickName(),req.getHeadPhoto(),req.getUserPhone() ,req.getSessionId());
    	}
         super.edit(req);
         return   CodeDataResp.valueOfSuccessEmptyData();
    }
  
	private static Set<String> FileSuffixImage = new HashSet<String>() {{
			add(".jpg");
			add(".png");
	}};
    
    @ApiOperation(value="上传头像")
    @RequestMapping(value="/upload/headImg", method= RequestMethod.POST)
    public CodeDataResp  upload(@RequestParam("file") MultipartFile uploadFile) {
    	String userId= ShiroUtil.getPrincipalUserId();
    	//获取文件名，获取文件后缀，检验文件是不是.jpg .png类型 校验文件大小 保存到本地，返回文件
    	String oldName=uploadFile.getOriginalFilename();
    	String suffix=oldName.substring(oldName.lastIndexOf("."), oldName.length());//文件名后缀
    	 if(!FileSuffixImage.contains(suffix)) 
         	return CodeDataResp.valueOfFailed("请选择jpg或png图片");
         Date  date= new Date();
         String dateStr = DateUtil.format(date, DatePattern.PURE_DATETIME_MS_PATTERN);
     	String fileName2 = dateStr.concat("_").concat(String.valueOf( CommonConstant.ImageAddFlag.incrementAndGet()));
		String fileName = fileName2.concat(".jpg");
		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("static");
		String uploadPath = userDir.concat(File.separator).concat(CommuntiyMenEnum.Avatar.getValue());
		String  returnPath=CommuntiyMenEnum.Avatar.getValue().concat("/").concat(fileName);
     	log.info("返回的文件路径：{0}",returnPath);
		  File folder = new File(uploadPath);
	        if (!folder.isDirectory()) 
	             folder.mkdirs();
            try {
            	 // 文件保存
				uploadFile.transferTo(new File(folder, fileName));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
           UserEntity u= this.getById(userId);
           u.setHeadPhoto(returnPath);
           this.updateById(u);
         return   CodeDataResp.valueOfSuccess(returnPath);
    }
    
    @ApiOperation(value="MP:批量冻结或解冻")
    @RequestMapping(value="/freezes", method= RequestMethod.POST)
    public CodeDataResp freezes(@RequestBody List<UserEntity> reqs) {
    	Assert.requireNonEmpty(reqs, "参数必传");
    	this.updateBatchById(reqs);
    	 return  CodeDataResp.valueOfSuccessEmptyData();
    }
    
    @ApiOperation(value="删除")
    @RequestMapping(value="/remove/{id}", method= RequestMethod.GET)
    @RequiresRoles(value={AccountType.ACCOUNT_TYPE_SYS_STAFF})
    public CodeDataResp remove(@PathVariable(name="id") String id) {
    			List<Integer> ids = new ArrayList<Integer>(1);
    			ids.add(Integer.parseInt(id));
    	    	removeBatch(ids);
        return  CodeDataResp.valueOfSuccessEmptyData();
    }
    
    
    @ApiOperation(value="批量删除")
    @RequestMapping(value="/removes", method= RequestMethod.POST)
    @RequiresRoles(value={AccountType.ACCOUNT_TYPE_SYS_STAFF})
    public CodeDataResp removes(@RequestBody @Validated @NotNull List<Integer> ids) {
    	removeBatch(ids);
    	return  CodeDataResp.valueOfSuccessEmptyData();
    }
    
    private void removeBatch( List<Integer> ids) {
//    	UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<UserEntity>();
//    	wrapper.lambda().set(UserEntity :: getStatus, 0).set(UserEntity :: getDelFlag, 1)
//    			.in(UserEntity :: getId, ids);
//    	this.removeBatch(ids);
    	super.removeByIds(ids);
//    	this.update(wrapper);
    }
    
    @ApiOperation(value="G:获取小程序openId")
    @RequestMapping(value="/setopenid", method= RequestMethod.POST)
    public CodeDataResp<UserInfoItem> setopenid(@RequestBody WxMaLoginReq req) {
    	UserEntity u= userService.getById(  ShiroUtil.getPrincipalUserId());
    	u.setNickName(req.getNickName());
		u.setHeadPhoto(req.getHeadPhoto());
		userService.getWxUserOpendId(u,req.getWxCode());
    	  return BeanMapper.copyRespDataItem(CodeDataResp.valueOfSuccess(u), UserInfoItem.class.getName());
    	
    }
    
    @ApiOperation(value="G:小程序授权获取微信手机号")
    @RequestMapping(value="/getWxPhoneCode", method= RequestMethod.GET)
    public CodeDataResp<String> getWxPhoneCode(@RequestParam("wxPhoneCode") String wxPhoneCode) {
    	UserEntity user = this.userService.getById(ShiroUtil.getPrincipalUserId());
    	String phone=	userService.getWxUserPhone(wxPhoneCode);
    	user.setUserPhone(phone);
    	this.userService.updateById(user);
    	
    	return CodeDataResp.valueOfSuccess(phone);
    }
    

    
}

